import time
import redis
from pynput.keyboard import Listener  as KeyboardListener
from pynput.mouse    import Listener  as MouseListener
from pynput.keyboard import Key
import math

is_pressed = False
origin_point = None

r = redis.Redis(db=0)


def on_press(key):
    r.set('user_move_timestamp', int(time.time()))

    print(key)
    print('{0} pressed'.format(key))
    if str(key).replace("'", "").isdigit():
        r.set('job_index', (int(str(key).replace("'", ""))))

    r.set('keyboard_input', str(key).replace("'", ""))


def on_move(x, y):
    r.set('user_move_timestamp', int(time.time()))

    if is_pressed:
        current_point = [x, y]

        radians = math.atan2(origin_point[1] - current_point[1], origin_point[0] - current_point[0])
        degrees = math.degrees(radians)
        distance = math.sqrt((origin_point[1] - current_point[1])**2 + (origin_point[0] - current_point[0])**2)

        max_d = 300

        if distance > max_d:
            distance = max_d
        else:
            distance = int(distance)

        max_speed = 22000

        if degrees < 0:
            if degrees > -10:
                degrees = 0
            elif degrees < -170:
                degrees = 180
        else:
            degrees = int(degrees)

        if degrees >= 90:
            left_speed = distance/max_d * max_speed
            right_speed = (1 - (degrees - 90)/90)*left_speed
        else:
            right_speed = distance/max_d * max_speed
            left_speed = (degrees/90)*right_speed

        if degrees < 0:
            left_speed = 0
            right_speed = 0

        r.set('forward_left_speed', int(left_speed))
        r.set('forward_right_speed', int(right_speed))
        # print("{0} {1}".format(left_speed, right_speed))
        # print("{0} {1}".format(degrees, distance))
        print("Mouse moved to ({0}, {1})".format(x, y))


def on_click(x, y, button, pressed):
    global is_pressed
    global origin_point

    if pressed:
        is_pressed = True
        origin_point = [x, y]

        print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
    else:
        is_pressed = False
        origin_point = None
        r.set('forward_left_speed', 0)
        r.set('forward_right_speed', 0)
        print('released')


def f(k):
    print('%s %d' % (k.name, k.scan_code))
    if (k.scan_code > 1)  and (k.scan_code < 12):
        r.set('job_index', (k.scan_code-1) % 10)
    else:
        r.set('keyboard_input', k.scan_code)


if __name__ == '__main__':
    #     keyboard.on_rele ase(f, suppress=True)
    #     time.sleep(0.1)

    with MouseListener(on_click=on_click, on_move=on_move) as listener:
        with KeyboardListener(on_press=on_press) as listener:
             listener.join()
